const api = require('../../../utils/api.js');
const regeneratorRuntime = require('../../../utils/runtime.js');
const config = require('../../../utils/config.js')
const util = require('../../../utils/utils.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    author: {
      _id: '',
      name: '',
      openId: '',
      role: 1,
      createTime: '',
      updateTime: ''
    },
    roles: [
      {
        name: '普通管理员',
        value: 1,
      },
      {
        name: '超级管理员',
        value: 0,
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    let authorId = options.id;
    if (authorId !== undefined && authorId != "") {
      let that = this
      api.getAuthorById(authorId, function(res){
        console.info('author detail -> ', res)
        that.setData({
          author: res.data
        })
      })
      
    }
  },

  /**
   * 保存
   * @param {*} e 
   */
  saveAuthor: async function(e) {

    wx.showLoading({
      title: '保存中...',
    })
   console.info('author data ->', this.data.author)
    let that = this;
    let author = this.data.author
    author.createTime = util.tsFormatTime(Date.now())
    author.updateTime = util.tsFormatTime(Date.now())
    console.log('input author ->', author)
    if (author._id === undefined || author._id == "") {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    if (author.name === undefined || author.name == "") {
      wx.showToast({
        title: '姓名不能为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    let result = await api.upsertAuthor(author)
    console.info('save author ->', result)
    if (result) {
      wx.hideLoading()
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 1500
      })
    }
  },


  onDataChange: function(e) {
    console.info('data change -> ', e)
    let author = this.data.author;
    switch(e.currentTarget.id) {
      case 'name': {
        author.name = e.detail.value
        break
      }
      case 'phoneNumber': {
        author._id = e.detail.value 
        break
      }
      case 'openId': {
        author.openId = e.detail.value
        break
      }
    }
    console.info('current change -> ', author)
    this.setData({
      author: author
    })
  },

  radioChange: function(e) {
    console.info('radio role -> ', e.detail.value)
    let author = this.data.author
    author.role = e.detail.value
    this.setData({
      author: author
    })
  },

  navBack: function(e) {
    wx.navigateBack({
      delta: 1
    })
  }, 
})